import {useBaseInfoWithOut} from "@/store/modules/base-info";
import {useSummaryCommentWithOut} from "@/store/modules/summary/comment";

const useBaseInfo = useBaseInfoWithOut();
const useSummaryComment = useSummaryCommentWithOut();
/**
 * 触发两种机制：
 * 1、异步带回调 通过回调的error来确认监听器执行失败
 * 2、同步无回调 任意监听器返回值（!result==true) 则表示监听器执行失败
 * @type {Map<string, function(*): Promise<unknown | void>>}
 */
const actionEventMap = new Map([
  ['AddNode', (params) => fireSyncEvent('beforeDealaddnode', params)],
  ['moreSign', (params) => fireSyncEvent('beforeDealaddnode', params)],
  ['RemoveNode', (params) => fireSyncEvent('beforeDealdeletenode', params)],
  ['Terminate', (params) => fireSyncEvent('beforeDealstepstop', params)],
  ['Cancel', (params) => fireSyncEvent('beforeDealCancel', params)],
  ['return', (params) => fireSyncEvent('beforeDealstepback', params)],
  ['specifiesReturn', (params) => fireSyncEvent('beforeDealspecifiesReturn', params)],
  ['specifiesReturnCreate', (params) => fireSyncEvent('beforeDealspecifiesReturn', params)],
  ['Comment', (params) => fireSyncEvent('beforeDealSaveWait', params)],
  ['ContinueSubmit', (params) => fireAsyncEvent('beforeSubmit', params)],
  ['beforeDealSubmit', (params) => fireAsyncEvent('beforeDealSubmit', params)],
  ['createMeeting', (params) => fireAsyncEvent('app-edit-btn-collaboration', params)],// 新建会议，给政务用
  ['relationDoc', (params) => fireAsyncEvent('beforeRelationDoc', params)],// 关联文档
  ['relationAttachment', (params) => fireAsyncEvent('beforeRelationAttachment', params)],// 关联附件
  ['transform', (params) => fireAsyncEvent('beforeTransform', params)],// 转事件
  ['transfer', (params) => fireAsyncEvent('beforeTransfer', params)],// 移交
  ['favorite', (params) => fireAsyncEvent('beforeFavorite', params)],// 收藏
  ['sign', (params) => fireAsyncEvent('beforeSign', params)],// 签章
  ['doZCDB', (params) => fireAsyncEvent('beforeDoZCDB', params)],// 暂存待办
  ['print', (params) => fireAsyncEvent('beforeDoPrint', params)],// 打印
  ['beforSendColl', (params) => fireSyncEvent('beforSendColl', params)],// 发起协同
  ['summary-leavePage', (params) => fireAsyncEvent('summary-leavePage', params)],// 发起协同
  ['newColl-leavePage', (params) => fireAsyncEvent('collaboration-leavePage', params)],// 发起协同
  ['thirdPartyHandle', (params) => fireAsyncEvent('thirdPartyHandle', params)],// 三方Listener接口拦截
]);

/**
 * 致迈的特殊埋点 = =！
 *
 * */
const customManageEmitMap = new Map(
  [
    ['beforSendColl', (params) => customManageEmitter('collaboration-preSubmit', params)],//协同发起事件 collaboration-preSubmit
    ['summary-leavePage', (params) => customManageEmitter('summary-leavePage', params)],//详情页面离开
    ['newColl-leavePage', (params) => customManageEmitter('newColl-leavePage', params)],//新建页面页面离开
    ['return', (params) => customManageEmitter('summary-stepBack', params)],//流程回退-summary-stepBack
    ['Terminate', (params) => customManageEmitter('summary-stepStop', params)],//流程回退-summary-stepStop
    ['ContinueSubmit', (params) => customManageEmitter('summary-beforePreSubmit', params)],//处理提交前-summary-beforePreSubmit
    ['Cancel', (params) => customManageEmitter('summary-cancel', params)],//撤销-summary-cancel
  ]
)

export async function fireEvent(actionCode, params) {
  let handler = actionEventMap.get(actionCode);
  if (!handler) {
    //匹配不到，认为传入的直接就是事件名称，执行事件同步
    return fireSyncEvent(actionCode, params);
  }
  let eventHook = await handler(params);
  if (!eventHook || eventHook === false) {
    return Promise.resolve(eventHook);
  }
  //开始customManageHook
  let customManageHandler = customManageEmitMap.get(actionCode);
  if (!customManageHandler) {
    return Promise.resolve(eventHook);
  }
  return customManageHandler(params);
}

function customManageEmitter(actionCode, params) {
  if (!window.customManage) {
    console.error('no customManage js inject');
    return;
  }
  let fnx = window._getZWIframe();
  Object.assign(params, colExtendInf());
  return new Promise(resolve => {
    window.customManage.eventEmit(
      {
        name: actionCode,
        beforeParams: [{
          contentDataId: fnx?.contentAPI?.getContentDataId() || '',
          affairId: params.affairId,
          colExtendInfo: params,
        }]
      },
      (handler) => {
        console.log(`customManageEmitter hook success ->${actionCode}`, arguments);
        resolve(true);
        handler.next();
      },
      () => {
        console.log(`customManageEmitter hook failed ->${actionCode}`, arguments);
        resolve(false);
      },
    )
  })
}

/**
 * 触发同步事件
 * @param eventName
 * @param params
 * @returns {Promise<unknown>}
 */
function fireSyncEvent(eventName, params = {}) {
  const {success} = params;
  params.success = null;
  return new Promise((resolve) => {
    let trigger = doTrigger(eventName, params)
    if (!trigger) {
      return resolve(false);
    }
    if (typeof success === 'function'){
      success.call(this, params);
    }
    return  resolve(true);
  }).catch(error => {
    console.log(`fireEvent[${eventName}] error`, error);
  })
}


/**
 * 触发异步事件
 * @param eventName
 * @param params
 * @returns {Promise<unknown>|boolean}
 */
function fireAsyncEvent(eventName, params = {}) {
  if (!eventName) return true;
  const {success,error}=params;
  return new Promise((resolve) => {
    doTrigger(eventName, {
      ...params,
      success() {
        if (typeof success === 'function'){
          success.call(this, params);  
        }
        resolve(true);
      },
      error() {
        if (typeof error === 'function'){
          error.call(this, params);
        }
        resolve(false);
      },
    })
  }).catch(error => {
    console.log(`fireEvent[${eventName}] error`, error);
  })
}


/**
 * TODO 后续有新机制 替换掉原有的$.ctp.trigger /$.ctp.bind
 * @param eventName
 * @param params
 * @returns {*}
 */
function doTrigger(eventName, params) {
  console.log("$.ctp.trigger", eventName);
  return $.ctp.trigger(eventName, params);
}

/**
 * 组装协同事件参数
 * @param businessData
 * @param globalData
 * @param params
 */
export function getCollEventParams(businessData, globalData, params={}) {
  let capContent = params?.formParamData?.data?.content || {};
  let dealComment = params?.collaborationDealParamData?.comment || {};
  let fnx = window._getZWIframe();
  const {summary = {}, affair = {}, workflow = {}, nodePolicy = {},template={}} = businessData || {};
  return {
    summaryID: summary.id || '', // 协同ID(兼容旧的事件扩展)
    affairID: affair.id || '', // 事项ID(兼容旧的事件扩展)
    summaryId: summary.id || '', // 协同ID
    affairId: affair.id || '', // 事项ID
    cap4Flag: !!globalData.isCap4, // 是否cap4表单
    formId: summary.formAppid || '', // 表单ID
    formRecordId: affair.formRecordid || fnx?.contentAPI?.getContentDataId() || '', // 表单数据ID
    templateId: affair.templateId || template.id || '', // 表单模板ID
    rightId: capContent.rightId || useBaseInfo.baseInfo?.zwIframe?.cap4?.rightId || '', // 权限ID
    ActivityId: affair.activityId || workflow.activityId || '', // 节点ID
    _summaryActivityId: affair.activityId || workflow.activityId || '', // 节点ID
    processId: affair.processId || '', // 流程ID
    caseId: affair.caseId || '', // 实例ID
    startMemberId: affair.senderId || '', // 发起人ID
    CurrentUserId: affair.memberId || '', // 当前登录人ID
    bodyType: affair.bodyType || '', // 表单类型
    affairState: affair.state || '', // 流程状态
    affairSubState: affair.subState || '', // 流程状态
    nodepolicy: affair.nodePolicy || nodePolicy.defaultNodeName || '', // 节点类型
    nodepolicyName: nodePolicy.nodePolicyName || nodePolicy.defaultNodeLable || '', // 节点名称
    workItemId: affair.subObjectId || '', //
    matchRequestToken: workflow.matchRequestToken || '', //
    method: globalData.method || '', // 打开模版的方式
    attitude: dealComment?.attitude?.code || '', // 处理态度
    nodeName: affair.nodeName || '',// 自定义节点名称
    isNew: !globalData.isSummary, // 是否发起
    isHasDealPage: !!globalData.isSummary, // 是否处理界面
    isPigeonhole: useSummaryComment.isPigeonhole,//是否处理后归档
    comment: {
      attitudeType: dealComment?.attitude?.subject,
      content: dealComment.textContent || dealComment.commentText
    },
    currentNodeInfo: {
      nodeId: affair.activityId || workflow.activityId || '',
      nodeName: affair.activityId || workflow.activityId || '',
      nodeType: nodePolicy.nodePolicyName || nodePolicy.defaultNodeLable || ''
    }
  }
}

/**
 * customManageEmit始终有的参数
 *
 */
function colExtendInf() {
  let businessData = useBaseInfo?.baseInfo?.businessData || {};
  const {summary = {}, affair = {}, workflow = {}} = businessData || {};
  let fnx = window._getZWIframe();
  return {
    formAppid: summary.formAppid || '',
    formContentId: affair.formRecordid || fnx?.contentAPI?.getContentDataId() || '',
    contentDataId: fnx?.contentAPI?.getContentDataId() || '',
    affairId: affair.id,
    summaryId: summary.id,
    templateId: affair.templateId || summary.templateId || '',
    wfCaseId: affair.caseId || '',
    wfActivityId: affair.activityId || workflow.activityId || '', // 节点ID,
    _summaryProcessId: affair.processId || '', // 流程ID,
    _summaryActivityId: affair.activityId || workflow.activityId || '', // 节点ID
  }
}
